package lib.quasar.widget.warning;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import lib.quasar.util.DimenUtil;

/**
 * description: 警告信息
 * created by kalu on 2018/5/9 13:10
 */
public final class WarningView extends View {

    private final ValueAnimator mValueAnimator = new ValueAnimator();
    private final Paint mPaint = new Paint();

    private String mText;
    private float mAlpha = 1f;

    {
        mPaint.setAntiAlias(true);
        mPaint.setFilterBitmap(true);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setFakeBoldText(true);
        mPaint.setStrokeWidth(0f);
        mPaint.setColor(Color.RED);
        mPaint.setTextSize(DimenUtil.sp2px(14f));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextAlign(Paint.Align.CENTER);

        mValueAnimator.setFloatValues(1f, 0f, 1f, 0f);
        mValueAnimator.setDuration(1500);
        mValueAnimator.addUpdateListener(animation -> {
            mAlpha = (float) animation.getAnimatedValue();
            postInvalidate();
        });
    }

    public WarningView(Context context) {
        super(context);
    }

    public WarningView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public WarningView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        if (TextUtils.isEmpty(mText)) return;
        canvas.save();
        canvas.drawText(mText, getWidth() / 2, getHeight() / 2, mPaint);
        canvas.restore();
        setAlpha(mAlpha);
    }

    public void setWarning(String text) {
        mValueAnimator.cancel();
        setAlpha(1f);
        mText = text;
        mValueAnimator.start();
    }
}
